﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Windows.Media.Imaging;
using CodeXtremeAppsSubmissionByJET.ClassFiles;
using System.Xml.Linq;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Tasks;


namespace CodeXtremeAppsSubmissionByJET
{
    public partial class MainPage : PhoneApplicationPage
    {
        //itemIndecies
        int placeIdShioked;
        int hotelIdShioked;

        //GPS Watcher
        GeoCoordinateWatcher gpsWatcher;
        GeoCoordinate gpsCoordinate;
        string gpsAddress;

        //ShakeDetector
        private ShakeDetector shiokDetector;

        //DataSet stored here!!!
        List<Place> placeList;
        List<Hotel> hotelList;
        //List<Event> eventList;
        //List<Food> foodList;

        // Constructor
        public MainPage()
        {
            InitializeComponent();


            //initialize the shiokdetector
            shiokDetector = new ShakeDetector();
            shiokDetector.ShakeEvent += new EventHandler<EventArgs>(shiokDetector_ShakeEvent);
            shiokDetector.Start();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            tbkSite.MouseLeftButtonUp += new MouseButtonEventHandler(tbkSite_MouseLeftButtonUp);
            tbkTel.MouseLeftButtonUp += new MouseButtonEventHandler(tbkTel_MouseLeftButtonUp);
            tbkSiteH.MouseLeftButtonUp += new MouseButtonEventHandler(tbkSiteH_MouseLeftButtonUp);
            tbkTelH.MouseLeftButtonUp += new MouseButtonEventHandler(tbkTelH_MouseLeftButtonUp);
        }

        void tbkTelH_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            PhoneCallTask phoneTask = new PhoneCallTask();
            phoneTask.DisplayName = hotelName.Text;
            phoneTask.PhoneNumber = tbkTelH.Text;
            phoneTask.Show();
        }

        void tbkSiteH_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WebBrowserTask ieTask = new WebBrowserTask();
            ieTask.URL = tbkSiteH.Text;
            ieTask.Show();
        }

        void tbkTel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            PhoneCallTask phoneTask = new PhoneCallTask();
            phoneTask.DisplayName = placeName.Text;
            phoneTask.PhoneNumber = tbkTel.Text;
            phoneTask.Show();
        }

        void btnDirectionP_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask ieTask = new WebBrowserTask();
            ieTask.URL = "http://gothere.sg/maps#q:" + gpsCoordinate.Latitude + "%20%2F%20" + gpsCoordinate.Longitude + "%20to%20" + placeName.Text;
            ieTask.Show();
        }

        void tbkSite_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WebBrowserTask ieTask = new WebBrowserTask();
            ieTask.URL = tbkSite.Text;
            ieTask.Show();
        }

        void shiokDetector_ShakeEvent(object sender, EventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
                {
                    if (panoMain.SelectedItem == panoItemPlaces)
                    {
                        if (placeIdShioked == placeList[placeList.Count - 1].PlaceID)
                        {
                            placeName.Text = placeList[0].Name;
                            tbkAddress.Text = placeList[0].Address1 + "\r\n" + placeList[0].Address2;
                            tbkSite.Text = "http://" + placeList[0].URL.Trim();
                            tbkTel.Text = placeList[0].Tel;
                            placeIdShioked = placeList[0].PlaceID;
                        }
                        else
                        {
                            for (int k = 0; k < placeList.Count; k++)
                            {
                                if (placeList[k].PlaceID == placeIdShioked)
                                {
                                    placeName.Text = placeList[k + 1].Name;
                                    tbkAddress.Text = placeList[k + 1].Address1 + "\r\n" + placeList[k + 1].Address2;
                                    tbkSite.Text = "http://" + placeList[k + 1].URL.Trim();
                                    tbkTel.Text = placeList[k + 1].Tel;
                                    placeIdShioked = placeList[k + 1].PlaceID;
                                    break;
                                }
                            }
                        }
                    }
                    else if (panoMain.SelectedItem == panoItemHotels)
                    {
                        if (hotelIdShioked == hotelList[hotelList.Count - 1].HotelID)
                        {
                            hotelName.Text = hotelList[0].Name;
                            tbkAddressH.Text = hotelList[0].Address;
                            tbkSiteH.Text = "http://" + hotelList[0].URL.Trim();
                            tbkTelH.Text = hotelList[0].Tel;
                            hotelIdShioked = hotelList[0].HotelID;
                        }
                        else
                        {
                            for (int k = 0; k < hotelList.Count; k++)
                            {
                                if (hotelList[k].HotelID == hotelIdShioked)
                                {
                                    hotelName.Text = hotelList[k + 1].Name;
                                    tbkAddressH.Text = hotelList[k + 1].Address;
                                    tbkSiteH.Text = "http://" + hotelList[k + 1].URL.Trim();
                                    tbkTelH.Text = hotelList[k + 1].Tel;
                                    hotelIdShioked = hotelList[k + 1].HotelID;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        shiokDetector.Stop();
                        MessageBox.Show("Shiok!Singapore\r\nVersion 1.0\r\nA CodeXtremeApps washaout\r\n\r\nDevelopers:\r\nEric Liu, Justina Lee, Cris Zheng\r\n\r\nFeedback & Enquiry:\r\nliulongyin@hotmail.com\r\n\r\nThanks to:\r\nTemasek Polytechnic\r\nFriends & tutors\r\nMicrosoft Student Parners\r\nProject Nimbus\r\n\r\nThank you for downloading this app.", "about...", MessageBoxButton.OK);
                        shiokDetector.Start();
                    }
                });
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

            BitmapImage switchPanoBgImage;
            if (DateTime.Now.Hour >= 18 || DateTime.Now.Hour < 6)
            {
                switchPanoBgImage = new BitmapImage(new Uri("PanoramaBackgroundAlt.png", UriKind.Relative));
            }
            else
            {
                switchPanoBgImage = new BitmapImage(new Uri("PanoramaBackground.png", UriKind.Relative));
            }
            ImageBrush switchPanoBgImageBrush = new ImageBrush();
            switchPanoBgImageBrush.ImageSource = switchPanoBgImage;
            panoMain.Background = switchPanoBgImageBrush;

            if (gpsWatcher == null)
            {
                gpsWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy
                gpsWatcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal
                gpsWatcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(gpsWatcher_StatusChanged);
                gpsWatcher.Start();
            }

        }

        void gpsWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (gpsWatcher.Status)
            {
                case GeoPositionStatus.Disabled:
                    // The Location Service is disabled or unsupported.
                    // Check to see whether the user has disabled the Location Service.
                    if (gpsWatcher.Permission == GeoPositionPermission.Denied)
                    {
                        // The user has disabled the Location Service on their device.
                        MessageBox.Show("You have disabled location access. Please check the settings and try again.", "Error", MessageBoxButton.OK);
                    }
                    else
                    {
                        MessageBox.Show("location access is not functioning. Please check the settings and try again.", "Error", MessageBoxButton.OK);
                    }
                    //App.Quit();
                    break;

                case GeoPositionStatus.Initializing:
                    // The Location Service is initializing.
                    // Disable the Start Location button.
                    panoMain.IsEnabled = false;
                    break;

                case GeoPositionStatus.NoData:
                    // The Location Service is working, but it cannot get location data.
                    // Alert the user and enable the Stop Location button.
                    MessageBox.Show("location data is not available now. Please wait.\nIf the transmission takes too long, exit the app and try again in a better location.", "Error", MessageBoxButton.OK);
                    break;

                case GeoPositionStatus.Ready:
                    // The Location Service is working and is receiving location data.
                    // Show the current position and enable the Stop Location button.
                    // main program flow starts here!!!!



                    // retrieve all data
                    retrievePlace();
                    //retrieveEvent();

                    // make changes to UI
                    panoMain.IsEnabled = true;
                    gpsCoordinate = gpsWatcher.Position.Location;
                    gpsWatcher.Stop();


                    mapHere.Center = gpsCoordinate;
                    mapHere.ZoomLevel = 17;
                    mapHere.ZoomBarVisibility = System.Windows.Visibility.Visible;
                    Pushpin pushpinCurrent = new Pushpin();
                    pushpinCurrent.Location = gpsCoordinate;

                    getUserAddress();

                    pushpinCurrent.Content = "You";
                    pushpinCurrent.Visibility = System.Windows.Visibility.Visible;
                    mapHere.Children.Add(pushpinCurrent);
                    break;
            }
        }

        public void retrievePlace()
        {
            string url = "http://api.projectnimbus.org/stbodataservice.svc/PlaceSet";
            string accountKey = "mlU2HLatho";
            string uniqueUserId = "ab2608c9-25f1-46d2-99b9-a798d3a6525b";
            WebClient svcPlace = new WebClient();
            svcPlace.Headers["AccountKey"] = accountKey;
            svcPlace.Headers["UniqueUserID"] = uniqueUserId;
            svcPlace.DownloadStringCompleted += new DownloadStringCompletedEventHandler(svcPlace_DownloadStringCompleted);
            svcPlace.DownloadStringAsync(new Uri(url));
        }

        void svcPlace_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string rawXml = e.Result;
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                XNamespace dNS = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                XNamespace mNS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
                XNamespace gNS = "http://www.georss.org/georss";
                List<Place> results = (from item in XElement.Parse(rawXml).Descendants(atomNS + "entry")
                                       let places = item.Element(atomNS + "content").Element(mNS + "properties")
                                       select new Place()
                                       {
                                           PlaceID = Convert.ToInt32(places.Element(dNS + "PlaceID").Value),
                                           Name = places.Element(dNS + "Name").Value,
                                           Address1 = places.Element(dNS + "Address1").Value,
                                           Address2 = places.Element(dNS + "Address2").Value,
                                           PostalCode = places.Element(dNS + "PostalCode").Value,
                                           Tel = places.Element(dNS + "Tel").Value,
                                           URL = places.Element(dNS + "URL").Value,
                                           OperatingHours = places.Element(dNS + "OperatingHours").Value,
                                           Latitude = Convert.ToDouble(places.Element(dNS + "Latitude").Value),
                                           Longitude = Convert.ToDouble(places.Element(dNS + "Longitude").Value),
                                           Distance = Convert.ToDouble(places.Element(dNS + "Distance").Value),
                                           Summary = places.Element(dNS + "Summary").Value,
                                           CreateDate = Convert.ToDateTime(places.Element(dNS + "CreateDate").Value)
                                       }).ToList<Place>();

                // Store the result somewhere !!!!
                placeList = results;

                // sort according to distance!!!
                if (placeList.Count > 1)
                {
                    for (int i = 0; i < placeList.Count - 1; i++)
                    {
                        for (int j = 0; j < placeList.Count - i - 1; j++)
                        {
                            double distance1 = Math.Sqrt(Math.Pow((placeList[j].Latitude - gpsCoordinate.Latitude), 2) + Math.Pow((placeList[j].Longitude - gpsCoordinate.Longitude), 2));
                            double distance2 = Math.Sqrt(Math.Pow((placeList[j + 1].Latitude - gpsCoordinate.Latitude), 2) + Math.Pow((placeList[j + 1].Longitude - gpsCoordinate.Longitude), 2));
                            if (distance1 > distance2)
                            {
                                Place tempLoc = placeList[j];
                                placeList[j] = placeList[j + 1];
                                placeList[j + 1] = tempLoc;
                            }
                        }
                    }
                }

                foreach (Place aPlace in placeList)
                {
                    Pushpin temp = new Pushpin();
                    temp.Location = new GeoCoordinate(aPlace.Latitude, aPlace.Longitude);
                    temp.Content = aPlace.Name;
                    temp.Background = new SolidColorBrush(Colors.Gray);
                    temp.Visibility = System.Windows.Visibility.Visible;
                    mapHere.Children.Add(temp);
                }
            }

            placeName.Text = placeList[0].Name;
            tbkAddress.Text = placeList[0].Address1 + "\r\n" + placeList[0].Address2;
            tbkSite.Text = "http://" + placeList[0].URL.Trim();
            tbkTel.Text = placeList[0].Tel;
            placeIdShioked = placeList[0].PlaceID;
            retrieveHotel();
        }

        public void retrieveHotel()
        {
            string url = "http://api.projectnimbus.org/stbodataservice.svc/HotelSet";
            string accountKey = "mlU2HLatho";
            string uniqueUserId = "ab2608c9-25f1-46d2-99b9-a798d3a6525b";
            WebClient svcHotel = new WebClient();
            svcHotel.Headers["AccountKey"] = accountKey;
            svcHotel.Headers["UniqueUserID"] = uniqueUserId;
            svcHotel.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(svcHotel_DownloadStringCompleted);
            svcHotel.DownloadStringAsync(new Uri(url));
        }
        void svcHotel_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string rawXml = e.Result;
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                XNamespace dNS = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                XNamespace mNS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
                XNamespace gNS = "http://www.georss.org/georss";
                List<Hotel> results = (from item in XElement.Parse(rawXml).Descendants(atomNS + "entry")
                                       let hotels = item.Element(atomNS + "content").Element(mNS + "properties")
                                       select new Hotel()
                                       {
                                           HotelID = Convert.ToInt32(hotels.Element(dNS + "HotelID").Value),
                                           Name = hotels.Element(dNS + "Name").Value,
                                           Address = hotels.Element(dNS + "Address").Value,
                                           PostalCode = hotels.Element(dNS + "PostalCode").Value,
                                           URL = hotels.Element(dNS + "URL").Value,
                                           Tel = hotels.Element(dNS + "Tel").Value,
                                           Latitude = Convert.ToDouble(hotels.Element(dNS + "Latitude").Value),
                                           Longitude = Convert.ToDouble(hotels.Element(dNS + "Longitude").Value),
                                           Distance = Convert.ToDouble(hotels.Element(dNS + "Distance").Value),
                                           Summary = hotels.Element(dNS + "Summary").Value,
                                           CreateDate = Convert.ToDateTime(hotels.Element(dNS + "CreateDate").Value)
                                       }).ToList<Hotel>();
                hotelList = results;
                // sort according to distance!!!
                if (hotelList.Count > 1)
                {
                    for (int i = 0; i < hotelList.Count - 1; i++)
                    {
                        for (int j = 0; j < hotelList.Count - i - 1; j++)
                        {
                            double distance1 = Math.Sqrt(Math.Pow((hotelList[j].Latitude - gpsCoordinate.Latitude), 2) + Math.Pow((hotelList[j].Longitude - gpsCoordinate.Longitude), 2));
                            double distance2 = Math.Sqrt(Math.Pow((hotelList[j + 1].Latitude - gpsCoordinate.Latitude), 2) + Math.Pow((hotelList[j + 1].Longitude - gpsCoordinate.Longitude), 2));
                            if (distance1 > distance2)
                            {
                                Hotel tempLoc = hotelList[j];
                                hotelList[j] = hotelList[j + 1];
                                hotelList[j + 1] = tempLoc;
                            }
                        }
                    }
                }

                foreach (Hotel aHotel in hotelList)
                {
                    Pushpin temp = new Pushpin();
                    temp.Location = new GeoCoordinate(aHotel.Latitude, aHotel.Longitude);
                    temp.Content = aHotel.Name;
                    temp.Background = new SolidColorBrush(Colors.Orange);
                    temp.Visibility = System.Windows.Visibility.Visible;
                    mapHere.Children.Add(temp);
                }


                //retrieveFood();
            }

            hotelName.Text = hotelList[0].Name;
            tbkAddressH.Text = hotelList[0].Address;
            tbkTelH.Text = hotelList[0].Tel;
            tbkSiteH.Text = "http://" + hotelList[0].URL;
            hotelIdShioked = hotelList[0].HotelID;

        }

        private void btnDirectionP_Click_1(object sender, RoutedEventArgs e)
        {
            string fromAddress = gpsAddress;
            string toAddress = placeName.Text;
            WebBrowserTask ieTask = new WebBrowserTask();
            ieTask.URL = "http://gothere.sg/m/directions?f=" + fromAddress + "%26t=" + toAddress;
            ieTask.Show();
        }

        private void getUserAddress()
        {
            string gMapsApiKey = "ABQIAAAAb7AUqCcX-J7TWenRtj0sYBQcncWBduB6oMO1yXY5lQPHmlPd5RSyYtHCIyW35uVl4sathyObOdTjAQ";
            string lat = gpsCoordinate.Latitude.ToString();
            string lon = gpsCoordinate.Longitude.ToString();
            string sPath = "http://maps.google.com/maps/geo?q=" + lat + "," + lon + "&output=csv&key=" + gMapsApiKey;

            try
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
                client.DownloadStringAsync(new Uri(sPath));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string[] eResult = e.Result.ToString().Split(',');
                string eStreetAddress = eResult[2];
                string[] eAddress = eStreetAddress.Split('"');
                gpsAddress = eAddress[1];
                
            }
            catch (Exception)
            {
                gpsAddress = "Location data is unavailable.";
            }
        }

        private void btnDirectionH_Click(object sender, RoutedEventArgs e)
        {
            string fromAddress = gpsAddress;
            string toAddress = hotelName.Text;
            WebBrowserTask ieTask = new WebBrowserTask();
            ieTask.URL = "http://gothere.sg/m/directions?f=" + fromAddress + "%26t=" + toAddress;
            ieTask.Show();
        }

        private void btnBingH_Click(object sender, RoutedEventArgs e)
        {
            SearchTask searchTask = new SearchTask();
            searchTask.SearchQuery = hotelName.Text + " +Singapore";
            searchTask.Show();
        }

        private void btnBingP_Click(object sender, RoutedEventArgs e)
        {
            SearchTask searchTask = new SearchTask();
            searchTask.SearchQuery = placeName.Text + " +Singapore";
            searchTask.Show();
        }

        //public void retrieveEvent()
        //{
        //    string url = "http://api.projectnimbus.org/stbodataservice.svc/EventSet";
        //    string accountKey = "mlU2HLatho";
        //    string uniqueUserId = "ab2608c9-25f1-46d2-99b9-a798d3a6525b";
        //    WebClient svcEvent = new WebClient();
        //    svcEvent.Headers["AccountKey"] = accountKey;
        //    svcEvent.Headers["UniqueUserID"] = uniqueUserId;
        //    //svcEvent.DownloadStringCompleted+=new DownloadStringCompletedEventHandler(svcEvent_DownloadStringCompleted);
        //    svcEvent.DownloadStringAsync(new Uri(url));
        //}
        //void svcEvent_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    if (e.Error == null)
        //    {
        //        string rawXml = e.Result;
        //        XNamespace atomNS = "http://www.w3.org/2005/Atom";
        //        XNamespace dNS = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        //        XNamespace mNS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
        //        XNamespace gNS = "http://www.georss.org/georss";
        //        List<Event> results = (from item in XElement.Parse(rawXml).Descendants(atomNS + "entry")
        //                               let events = item.Element(atomNS + "content").Element(mNS + "properties")
        //                               select new Event()
        //                               {
        //                                   EventID = Convert.ToInt32(events.Element(dNS + "EventID").Value),
        //                                   Organizer = events.Element(dNS + "Organizer").Value,
        //                                   Industry = events.Element(dNS + "Industry").Value,
        //                                   Name = events.Element(dNS + "Name").Value,
        //                                   StartDate = Convert.ToDateTime(events.Element(dNS + "StartDate").Value),
        //                                   EndDate = Convert.ToDateTime(events.Element(dNS + "EndDate").Value),
        //                                   Venue = events.Element(dNS + "Venue").Value,
        //                                   EstimatedAttendees = events.Element(dNS + "EstimatedAttendees").Value,
        //                                   EstimatedFloorArea = events.Element(dNS + "EstimatedFloorArea").Value,
        //                                   Contacts = events.Element(dNS + "Contacts").Value,
        //                                   OtherInformation = events.Element(dNS + "OtherInformation").Value,
        //                                   Summary = events.Element(dNS + "Summary").Value,
        //                                   CreateDate = Convert.ToDateTime(events.Element(dNS + "CreateDate").Value),
        //                                   Latitude = Convert.ToDouble(events.Element(dNS + "Latitude").Value),
        //                                   Longitude = Convert.ToDouble(events.Element(dNS + "Longitude").Value),
        //                                   Distance = Convert.ToDouble(events.Element(dNS + "Distance").Value)
        //                               }).ToList<Event>();
        //        eventList = results;
        //    }
        //}


        //public void retrieveFood()
        //{
        //    string url = "http://api.projectnimbus.org/hgwodataservice.svc/RestaurantSet";
        //    string accountKey = "mlU2HLatho";
        //    string uniqueUserId = "ab2608c9-25f1-46d2-99b9-a798d3a6525b";
        //    WebClient svcFood = new WebClient();
        //    svcFood.Headers["AccountKey"] = accountKey;
        //    svcFood.Headers["UniqueUserID"] = uniqueUserId;
        //    svcFood.DownloadStringCompleted += new DownloadStringCompletedEventHandler(svcFood_DownloadStringCompleted);
        //    svcFood.DownloadStringAsync(new Uri(url));
        //}

        //void svcFood_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    if (e.Error == null)
        //    {
        //        string rawXml = e.Result;
        //        XNamespace atomNS = "http://www.w3.org/2005/Atom";
        //        XNamespace dNS = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        //        XNamespace mNS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
        //        XNamespace gNS = "http://www.georss.org/georss";
        //        List<Food> results = (from item in XElement.Parse(rawXml).Descendants(atomNS + "entry")
        //                              let food = item.Element(atomNS + "content").Element(mNS + "properties")
        //                              select new Food()
        //                              {
        //                                  ID = Convert.ToInt32(food.Element(dNS + "ID").Value),
        //                                  FoodPlace = food.Element(dNS + "FoodPlace").Value,
        //                                  CuisineType = food.Element(dNS + "CuisineType").Value,
        //                                  POI = food.Element(dNS + "POI").Value,
        //                                  BlkHse = food.Element(dNS + "BlkHse").Value,
        //                                  StreetName = food.Element(dNS + "StreetName").Value,
        //                                  UnitNo = food.Element(dNS + "UnitNo").Value,
        //                                  BldgName = food.Element(dNS + "BldgName").Value,
        //                                  PostCode = Convert.ToDouble(food.Element(dNS + "PostCode").Value),
        //                                  Latitude = Convert.ToDouble(food.Element(dNS + "Latitude").Value),
        //                                  Longitude = Convert.ToDouble(food.Element(dNS + "Longitude").Value),
        //                                  PhoneNumber = food.Element(dNS + "PhoneNumber").Value,
        //                                  Web = food.Element(dNS + "Web").Value,
        //                                  Email = food.Element(dNS + "Email").Value,
        //                                  OverallRating = Convert.ToDouble(food.Element(dNS + "OverallRating").Value),
        //                                  PriceRange = food.Element(dNS + "PriceRange").Value,
        //                                  OperatingHours = food.Element(dNS + "OperatingHours").Value,
        //                                  Specialty = food.Element(dNS + "Specialty").Value,
        //                                  Brief = food.Element(dNS + "Brief").Value,
        //                                  Remarks = food.Element(dNS + "Remark").Value,
        //                                  MoreInfo = food.Element(dNS + "MoreInfo").Value,
        //                                  Url = food.Element(dNS + "Url").Value,
        //                                  Review = food.Element(dNS + "Review").Value,
        //                                  Distance = Convert.ToDouble(food.Element(dNS + "Distance").Value),
        //                                  Summary = food.Element(dNS + "Summary").Value,
        //                                  RecordStatusID = Convert.ToByte(food.Element(dNS + "RecordStatusID").Value),
        //                                  CreateDate = Convert.ToDateTime(food.Element(dNS + "CreateDate").Value),
        //                                  UpdateDate = Convert.ToDateTime(food.Element(dNS + "UpdateDate").Value)
        //                              }).ToList<Food>();
        //        foodList = results;


        //        // sort according to distance!!!
        //        if (foodList.Count > 1)
        //        {
        //            for (int i = 0; i < foodList.Count - 1; i++)
        //            {
        //                for (int j = 0; j < foodList.Count - i - 1; j++)
        //                {
        //                    double distance1 = Math.Sqrt(Math.Pow((foodList[j].Latitude - gpsCoordinate.Latitude), 2) + Math.Pow((foodList[j].Longitude - gpsCoordinate.Longitude), 2));
        //                    double distance2 = Math.Sqrt(Math.Pow((foodList[j + 1].Latitude - gpsCoordinate.Latitude), 2) + Math.Pow((foodList[j + 1].Longitude - gpsCoordinate.Longitude), 2));
        //                    if (distance1 > distance2)
        //                    {
        //                        Food tempLoc = foodList[j];
        //                        foodList[j] = foodList[j + 1];
        //                        foodList[j + 1] = tempLoc;
        //                    }
        //                }
        //            }
        //        }

        //        foreach (Food aFood in foodList)
        //        {

        //            Pushpin temp = new Pushpin();
        //            temp.Location = new GeoCoordinate(aFood.Latitude, aFood.Longitude);
        //            temp.Content = aFood.CuisineType;
        //            temp.Background = new SolidColorBrush(Colors.Orange);
        //            temp.Visibility = System.Windows.Visibility.Visible;
        //            mapHere.Children.Add(temp);
        //        }

        //        foodName.Text = foodList[0].FoodPlace;
        //        tbkAddressF.Text = foodList[0].BlkHse + " " + foodList[0].StreetName + "\r\n" + foodList[0].BldgName + " " + foodList[0].PostCode;
        //        tbkType.Text = foodList[0].CuisineType;
        //        tbkPrice.Text = foodList[0].PriceRange;
        //        tbkTelF.Text = foodList[0].PhoneNumber.Trim();
        //        tbkSiteF.Text = "http://" + foodList[0].Url;
        //    }
        //}
    }
}
